﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UDS.Entity;

namespace UDS.WebApp.SubModule
{
    public partial class PersonalFileListPage : Page
    {
        protected PFDirectoryInfo Current
        {
            get;
            private set;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // hook event handerls
            btn_Upload.Click += new EventHandler(On_Upload_Click);

            // get the information of the current directory
            int directoryId = QSUtil.GetPositiveInt32("DirectoryId", 0);
            RefreshUI(directoryId);
        }

        private void On_Upload_Click(object sender, EventArgs e)
        {
            try
            {
                PFFileInfo.Create(SiteContext.Current.UserID, Current.Id, fileUpload.PostedFile);
                RefreshUI(Current.Id);
            }
            catch (Exception ex)
            {
                SiteContext.Current.AlertException("保存文件失败", ex);
            }
        }

        protected static string FormatFileSize(int size)
        {
            int k = (int)Math.Ceiling(size / 1024d);
            return string.Format("{0:#,#} KB", k);
        }

        private void RefreshUI(int directoryId)
        {
            Current = PFDirectoryInfo.GetDirectory(SiteContext.Current.UserID, directoryId);
            if (Current == null)
            {
                // the root directory is also missing
                Current = new PFDirectoryInfo
                {
                    Name = "根目录",
                    Id = 0,
                    ParentId = 0,
                };
            }
            else
            {
                // show sub directories and files
                directoryRepeater.DataSource = Current.Directories;
                directoryRepeater.DataBind();

                fileRepeater.DataSource = Current.Files;
                fileRepeater.DataBind();
            }

            parentDirectoryRow.Visible = Current.Id > 0 && Current.Id != Current.ParentId;
        }
    }
}
